package com.k2data.k2app.common;

import com.k2data.k2app.domain.po.ModelDO;
import com.k2data.k2app.domain.po.TaskDTO;
import com.k2data.k2app.domain.vo.Device;
import com.k2data.k2app.mapper.ModelMapper;
import com.k2data.k2app.mapper.TaskMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * @author lidong9144@163.com 17-3-28.
 */
@Component
public class Validator {
//    @Autowired
//    private TaskMapper taskMapper;

    private final TaskMapper taskMapper;
    private final ModelMapper modelMapper;
    @Autowired
    public Validator(TaskMapper taskMapper,ModelMapper modelMapper) {
        this.taskMapper = taskMapper;
        this.modelMapper = modelMapper;
    }
    /**
     * 判断 taskId 是否存在
     *
     * @return {@code true} 存在 {@code false} 不存在
     */
    public boolean checkTaskID(Long taskId) {
        TaskDTO taskDTO = new TaskDTO();
        taskDTO.setId(taskId);
        return taskMapper.checkExist(taskDTO) != null;
    }

    /**
     * 判断 task 是否重复
     *
     * @return {@code true} 存在 {@code false} 不存在
     */
    public boolean checkTask(TaskDTO taskDO) {
        TaskDTO taskDO1 = taskMapper.getByCondition(taskDO);
        if(taskDO1 != null && !String.valueOf(taskDO1.getId()).equals(String.valueOf(taskDO.getId()))){
            List<Long> deviceIds = new ArrayList<>();
            List<Device> devices = taskDO1.getDevice();
            if(devices != null && devices.size()>0){
                devices.stream().forEach(item -> {
                    deviceIds.add(item.getDeviceId());
                });
            }
            List<Long> deviceIds1 = new ArrayList<>();
            List<Device> devices1 = taskDO.getDevice();
            if(devices1 != null && devices1.size()>0){
                devices1.stream().forEach(item -> {
                    deviceIds1.add(item.getDeviceId());
                });
            }
           return  deviceIds.containsAll(deviceIds1)&&deviceIds1.containsAll(deviceIds);
        }
        return false;
    }

    /**
     * 判断任务的模型是否可用
     * @param taskDTO
     * @return
     */
    public boolean checkIsUsed(TaskDTO taskDTO){
        ModelDO byModelId = modelMapper.getByModelId(taskDTO.getModelIdCopy());
        if (byModelId == null ||byModelId.getUseful()==1){
            return false;
        }
        return true;
    }
}
